package com.example.book.api;

import com.example.book.base.ApiBaseController;
import com.example.book.base.Result;
import com.example.book.common.utils.Constants;
import com.example.book.common.utils.RedisService;
import com.example.book.domain.wx.UserInfo;
import com.example.book.in.entity.BookCatalog;
import com.example.book.in.entity.BookInfo;
import com.example.book.in.entity.UserBookshelf;
import com.example.book.in.entity.UserReadRecord;
import com.example.book.in.service.BookCatalogService;
import com.example.book.in.service.BookInfoService;
import com.example.book.in.service.UserBookshelfService;
import com.example.book.in.service.UserReadRecordService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/book")
public class ApiUserBookshelfController extends ApiBaseController {

    private UserBookshelfService bookshelfService;
    private RedisService redisService;
    private BookInfoService bookInfoService;
    private BookCatalogService bookCatalogService;
    private UserReadRecordService readRecordService;

    public ApiUserBookshelfController(UserBookshelfService bookshelfService, RedisService redisService, BookInfoService bookInfoService,
                                      BookCatalogService bookCatalogService, UserReadRecordService readRecordService) {
        this.bookshelfService = bookshelfService;
        this.redisService = redisService;
        this.bookInfoService = bookInfoService;
        this.bookCatalogService = bookCatalogService;
        this.readRecordService = readRecordService;
    }

    /**
     * 加载用户书架列表
     *
     * @param bookshelf
     * @return
     */
    @GetMapping("/bookshelf/list")
    public Result findUserBookshelf(UserBookshelf bookshelf) {

        List<UserBookshelf> userBookshelves = bookshelfService.findList(bookshelf);

        List<Map<String, Object>> maps = new ArrayList<>();
        Map<String, Object> map = null;

        BookInfo bookInfo = new BookInfo();
        for (UserBookshelf ub : userBookshelves) {
            bookInfo.setId(ub.getBookInfoId());
            BookInfo bi = bookInfoService.get(bookInfo);
            if (bi != null) {
                map = new HashMap<>();
                map.put("id", bi.getId());
                map.put("picture", picture_url + bi.getBookCover());

                if (bi.getBookName().length() > 15) {
                    String idt = bi.getBookName().substring(0, 15) + "...";
                    map.put("name", idt);
                } else {
                    map.put("name", bi.getBookName());
                }
                map.put("author", bi.getBookAuthor().replace("作者：", ""));

                // 用户对该书籍的阅读记录
                UserReadRecord urr = new UserReadRecord();
                urr.setUserId(bookshelf.getUserId());
                urr.setBookInfoId(bi.getId());
                UserReadRecord record = readRecordService.findTheLastRecord(urr);

                // 没有阅读记录就是 0
                if (record == null){
                    map.put("percentage", 0);
                }else {
                    // 计算 阅读百分比 当前阅读数
                    BookCatalog bc = new BookCatalog();
                    bc.setId(record.getBookCatalogId());
                    BookCatalog current = bookCatalogService.get(bc);

                    // 查询书籍目录 最后一章 的索引
                    BookCatalog catalog = new BookCatalog();
                    catalog.setBookInfoId(bi.getId());
                    BookCatalog last = bookCatalogService.selectOrderByIndexDesc(catalog);

                    BigDecimal bd = new BigDecimal(current.getCatalogIndex()).divide(new BigDecimal(last.getCatalogIndex()), 2, BigDecimal.ROUND_HALF_UP);

                    map.put("percentage", bd);
                }

                maps.add(map);
            }
        }

        if (maps.size()<1){
            return Result.error("no data");
        }

        return Result.success(maps);
    }

    /**
     * 用户书籍加入书架
     *
     * @param bookshelf
     * @return
     */
    @PostMapping("/bookshelf")
    public Result addBookshelf(UserBookshelf bookshelf) {
        String token = getToken();
        if (StringUtils.isBlank(token)) {
            return Result.error("请登陆后操作");
        } else {
            UserInfo userInfo = (UserInfo) redisService.get(Constants.WX_API_TOKEN + token);
            if (userInfo == null) {
                return Result.error("请登陆后操作");
            }

            bookshelf.setUserId(userInfo.getUid());
            UserBookshelf ub = bookshelfService.get(bookshelf);
            if (ub != null) {
                return Result.error("已经在书架了");
            }
            bookshelfService.save(bookshelf);
        }
        return Result.success("已加入");
    }

}
